package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.LoginRespVo;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdPathFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
@Slf4j
public class AuthController {
    @Autowired
    private ThirdPathFeignService thirdPathFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Resource
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(String phone){
        //1、接口防刷

        //2、验证码60s内再次校验，redis
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if(StringUtils.isNotEmpty(redisCode)){
            String time = redisCode.split("_")[1];
            if((System.currentTimeMillis() - Long.parseLong(time)) < 60000){
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String code = UUID.randomUUID().toString().substring(0, 5)+"_"+System.currentTimeMillis();
        log.info("验证码code:"+code);
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone, code, 10, TimeUnit.MINUTES);
        thirdPathFeignService.sendCode(phone, code);

        return R.ok();
    }

    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo registVo, BindingResult result, RedirectAttributes redirectAttributes){
        if(result.hasErrors()) {
            Map<String, String> map = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //进行的注册
        String phoneRedis = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + registVo.getPhone());
        if(StringUtils.isEmpty(phoneRedis)){
            Map<String,String> map = new HashMap<>();
            map.put("msg", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", map);
            return "redirect:http://auth.gulimall.com/reg.html";
        }else{
            String[] s = phoneRedis.split("_");
            String cv = s[0], time = s[1];
            if(!registVo.getCode().equals(cv)){
                Map<String,String> map = new HashMap<>();
                map.put("msg", "验证码比较错误");
                redirectAttributes.addFlashAttribute("errors", map);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
            long l = System.currentTimeMillis() - Long.parseLong(time);
            log.info("相隔时间："+l);
            if(l > 60000){
                Map<String,String> map = new HashMap<>();
                map.put("msg", "验证码超时");
                redirectAttributes.addFlashAttribute("errors", map);
                return "redirect:http://auth.gulimall.com/reg.html";
            }else{
                //远程调用注册服务
                R regist = memberFeignService.regist(registVo);
                if(regist.getCode() == 0){
                    return "redirect:http://auth.gulimall.com/login.html";
                }else {
                    Map<String,String> map = new HashMap<>();
                    map.put("msg", regist.getData(new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors", map);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            }
        }
    }

    /**
     * 用户登录入口
     *
     * @param loginVo
     * @param redirectAttributes
     * @param session
     * @return
     */
    @PostMapping("/login")
    public String login(UserLoginVo loginVo, RedirectAttributes redirectAttributes, HttpSession session){
        R result = memberFeignService.login(loginVo);
        if(result.getCode() == 0){
            // TODO session信息
            LoginRespVo respVo = result.getData(new TypeReference<LoginRespVo>() {
            });
            session.setAttribute(AuthServerConstant.USER_LOGIN_SESSION_NAME, respVo);

            return "redirect:http://gulimall.com";
        }else {
            Map<String,String> map = new HashMap<>();
            map.put("msg", result.getData("msg", new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", map);
            return  "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
